#include "packetcapturer.h"
#include <QDateTime>
#include <QDebug>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pcap.h>

// 在macOS上，我们需要手动定义一些网络协议结构体，因为不同系统的头文件可能有所不同

// 以太网帧头结构体
struct EthernetHeader {
    u_char  destMac[6];    // 目的MAC地址
    u_char  srcMac[6];     // 源MAC地址
    u_short etherType;     // 以太网类型
};  // 共14字节

// 以太网类型常量
#define ETHERTYPE_IP        0x0800  // IPv4协议
#define ETHERTYPE_ARP       0x0806  // ARP协议
#define ETHERTYPE_IPV6      0x86DD  // IPv6协议

// IP头部结构体（简化版）
struct IPHeader {
    u_char  version_ihl;   // 版本和头部长度
    u_char  tos;           // 服务类型
    u_short total_length;  // 总长度
    u_short id;            // 标识符
    u_short frag_off;      // 碎片偏移
    u_char  ttl;           // 生存时间
    u_char  protocol;      // 协议
    u_short checksum;      // 校验和
    u_char  saddr[4];      // 源IP地址
    u_char  daddr[4];      // 目的IP地址
};  // 至少20字节

// IP协议号常量
#define PROTOCOL_TCP 6      // TCP协议
#define PROTOCOL_UDP 17     // UDP协议
#define PROTOCOL_ICMP 1     // ICMP协议
#define PROTOCOL_IGMP 2     // IGMP协议

// TCP头部结构体（简化版）
struct TCPHeader {
    u_short sourcePort;      // 源端口
    u_short destPort;        // 目的端口
    u_int   seq;             // 序列号
    u_int   ack;             // 确认号
    u_char  dataOffset;      // 数据偏移
    u_char  flags;           // 标志位
    u_short window;          // 窗口大小
    u_short checksum;        // 校验和
    u_short urgentPointer;   // 紧急指针
};  // 至少20字节

// TCP标志位常量
#define TCP_FLAG_FIN 0x01    // 结束连接
#define TCP_FLAG_SYN 0x02    // 同步序列
#define TCP_FLAG_RST 0x04    // 重置连接
#define TCP_FLAG_PSH 0x08    // 推送数据
#define TCP_FLAG_ACK 0x10    // 确认
#define TCP_FLAG_URG 0x20    // 紧急指针

// UDP头部结构体
struct UDPHeader {
    u_short sourcePort;      // 源端口
    u_short destPort;        // 目的端口
    u_short length;          // UDP长度
    u_short checksum;        // 校验和
};  // 8字节

// ICMP头部结构体（简化版）
struct ICMPHeader {
    u_char  type;            // 消息类型
    u_char  code;            // 消息代码
    u_short checksum;        // 校验和
    u_short id;              // 标识符
    u_short sequence;        // 序列号
};  // 8字节

// ARP头部结构体
struct ARPHeader {
    u_short hardwareType;    // 硬件类型
    u_short protocolType;    // 协议类型
    u_char  hardwareLen;     // 硬件地址长度
    u_char  protocolLen;     // 协议地址长度
    u_short operation;       // 操作类型
    u_char  senderMac[6];    // 发送方MAC地址
    u_char  senderIp[4];     // 发送方IP地址
    u_char  targetMac[6];    // 目标MAC地址
    u_char  targetIp[4];     // 目标IP地址
};  // 28字节

// ARP操作类型常量
#define ARP_OP_REQUEST 1      // ARP请求
#define ARP_OP_REPLY 2        // ARP响应

// IGMP头部结构体（简化版）
struct IGMPHeader {
    u_char  type;            // 消息类型
    u_char  maxResponseTime; // 最大响应时间
    u_short checksum;        // 校验和
    u_char  groupAddress[4]; // 组地址
};  // 8字节

// PacketCapturer构造函数
PacketCapturer::PacketCapturer(QObject *parent) 
    : QObject(parent),
      m_captureThread(nullptr),
      m_pcapHandle(nullptr),
      m_isCapturing(false)
{
    // 初始化工作已在初始化列表中完成
}

// PacketCapturer析构函数
PacketCapturer::~PacketCapturer()
{
    stopCapture();
    if (m_captureThread) {
        delete m_captureThread;
        m_captureThread = nullptr;
    }
}

// 获取可用网卡列表
QList<AdapterInfo> PacketCapturer::getAvailableAdapters()
{
    QList<AdapterInfo> adapters;
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_if_t *allDevices, *device;

    // 使用libpcap获取所有网络设备
    if (pcap_findalldevs(&allDevices, errbuf) == -1) {
        qDebug() << "Error finding devices: " << errbuf;
        return adapters;
    }

    // 遍历所有设备
    for (device = allDevices; device != nullptr; device = device->next) {
        AdapterInfo info;
        info.name = device->name;
        
        // 设置描述信息
        if (device->description != nullptr) {
            info.description = device->description;
        } else {
            info.description = QString("网络适配器 %1").arg(info.name);
        }

        adapters.append(info);
    }

    // 释放设备列表
    pcap_freealldevs(allDevices);
    return adapters;
}

// 开始捕获数据包
bool PacketCapturer::startCapture(const QString &adapterName)
{
    QMutexLocker locker(&m_mutex);
    
    if (m_isCapturing) {
        return false;
    }

    char errbuf[PCAP_ERRBUF_SIZE];

    // 打开网络设备进行捕获
    m_pcapHandle = pcap_open_live(adapterName.toStdString().c_str(), BUFSIZ, 1, 1000, errbuf);
    if (m_pcapHandle == nullptr) {
        QString errorMsg = QString("无法打开设备 %1: %2\n\n").arg(adapterName).arg(errbuf);
        
        // 在macOS上，捕获网络数据包通常需要管理员权限
        errorMsg += "提示：在macOS系统上，捕获网络数据包可能需要管理员权限。\n";
        errorMsg += "请尝试使用sudo命令以管理员身份运行程序，或在系统偏好设置中授予相应权限。";
        
        emit captureError(errorMsg);
        return false;
    }

    // 设置链路层数据类型
    if (pcap_datalink(m_pcapHandle) != DLT_EN10MB) {
        emit captureError(QString("设备 %1 不支持以太网捕获").arg(adapterName));
        pcap_close(m_pcapHandle);
        m_pcapHandle = nullptr;
        return false;
    }

    m_isCapturing = true;
    m_currentAdapter = adapterName;

    // 创建捕获线程
    m_captureThread = new QThread;
    
    // 连接信号和槽
    // 使用Qt::DirectConnection确保runCapture在新线程中执行
    connect(m_captureThread, &QThread::started, this, &PacketCapturer::runCapture, Qt::DirectConnection);
    connect(m_captureThread, &QThread::finished, m_captureThread, &QObject::deleteLater);
    
    // 不需要将整个PacketCapturer移动到线程中
    // 信号会自动通过Qt的事件循环机制正确传递到接收者所在线程
    // 特别是在Widget类中连接时，Qt会自动选择合适的连接类型
    
    // 当使用信号槽机制从一个线程发送到另一个线程时，
    // Qt会自动使用Qt::QueuedConnection确保安全
    
    m_captureThread->start();

    emit captureStarted();
    return true;
}

// 停止捕获数据包
void PacketCapturer::stopCapture()
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_isCapturing) {
        return;
    }

    // 关闭pcap句柄
    if (m_pcapHandle) {
        pcap_breakloop(m_pcapHandle);
        pcap_close(m_pcapHandle);
        m_pcapHandle = nullptr;
    }

    // 等待线程结束
    if (m_captureThread && m_captureThread->isRunning()) {
        m_captureThread->quit();
        m_captureThread->wait();
        m_captureThread = nullptr;
    }

    m_isCapturing = false;
    emit captureStopped();
}

// 检查是否正在捕获
bool PacketCapturer::isCapturing() const
{
    QMutexLocker locker(const_cast<QMutex*>(&m_mutex));
    return m_isCapturing;
}

// 线程运行函数，实际执行捕获逻辑
void PacketCapturer::runCapture()
{
    // 开始捕获数据包
    int result = pcap_loop(m_pcapHandle, 0, packetHandler, reinterpret_cast<u_char*>(this));
    
    // 捕获结束后清理
    if (result == 0) {
        // 正常结束
        qDebug() << "捕获结束";
    } else if (result == -1) {
        // 发生错误
        emit captureError(QString("捕获错误: %1").arg(pcap_geterr(m_pcapHandle)));
    } else if (result == -2) {
        // 被中断
        qDebug() << "捕获被中断";
    }
    
    // 确保线程结束时清理资源
    QMetaObject::invokeMethod(this, "stopCapture", Qt::QueuedConnection);
}

// 捕获回调函数
void PacketCapturer::packetHandler(u_char *userData, const struct pcap_pkthdr *pkthdr, const u_char *packet)
{
    PacketCapturer *capturer = reinterpret_cast<PacketCapturer*>(userData);
    
    // 解析数据包
    PacketInfo packetInfo = parsePacket(packet, pkthdr->len);
    
    // 发射信号通知UI更新
    emit capturer->packetCaptured(packetInfo);
}

// 解析数据包
PacketInfo PacketCapturer::parsePacket(const u_char *packetData, int length) {
    PacketInfo packet;
    
    // 设置基本信息
    packet.index = 0; // 序号将在Widget类中设置
    
    // 设置时间戳
    packet.timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    packet.length = length;
    
    // 解析以太网帧头
    EthernetHeader *ethHeader = reinterpret_cast<EthernetHeader*>(const_cast<u_char*>(packetData));
    
    // 格式化MAC地址
    char sourceMac[18], destMac[18];
    snprintf(sourceMac, sizeof(sourceMac), "%02x:%02x:%02x:%02x:%02x:%02x",
             ethHeader->srcMac[0], ethHeader->srcMac[1], ethHeader->srcMac[2],
             ethHeader->srcMac[3], ethHeader->srcMac[4], ethHeader->srcMac[5]);
    snprintf(destMac, sizeof(destMac), "%02x:%02x:%02x:%02x:%02x:%02x",
             ethHeader->destMac[0], ethHeader->destMac[1], ethHeader->destMac[2],
             ethHeader->destMac[3], ethHeader->destMac[4], ethHeader->destMac[5]);
    
    packet.sourceMac = sourceMac;
    packet.destMac = destMac;
    
    // 根据以太网类型进行不同的解析
    u_short etherType = ntohs(ethHeader->etherType);
    
    // 填充数据链路层详情
    packet.linkLayerDetail = QString("源MAC地址: %1\n").arg(packet.sourceMac) +
                            QString("目的MAC地址: %1\n").arg(packet.destMac);
    
    switch (etherType) {
    case ETHERTYPE_IP:
        packet.linkLayerDetail += "类型: IPv4";
        parseIPv4Packet(packetData, length, packet);
        break;
    case ETHERTYPE_ARP:
        packet.linkLayerDetail += "类型: ARP";
        parseARPPacket(packetData, length, packet);
        break;
    case ETHERTYPE_IPV6:
        packet.linkLayerDetail += "类型: IPv6";
        parseIPv6Packet(packetData, length, packet);
        break;
    default:
        packet.linkLayerDetail += QString("类型: 未知(0x%1)").arg(etherType, 0, 16);
        packet.protocol = "未知";
        packet.networkLayerDetail = "网络层数据（无法解析）";
        packet.transportLayerDetail = "传输层数据（无法解析）";
        packet.applicationLayerDetail = "应用层数据（无法解析）";
        break;
    }
    
    // 添加原始数据包数据
    packet.rawData = QByteArray(reinterpret_cast<const char*>(packetData), length);
    
    return packet;
}

// 解析IPv4数据包
void PacketCapturer::parseIPv4Packet(const u_char *packetData, int length, PacketInfo &packet)
{
    // 解析IP头部
    const u_char *ipHeaderData = packetData + sizeof(EthernetHeader);
    
    // 检查是否有足够的长度来解析IP头部
    if (length >= static_cast<int>(sizeof(EthernetHeader) + sizeof(IPHeader))) {
        const IPHeader *ipHeader = reinterpret_cast<const IPHeader*>(ipHeaderData);
        
        // 格式化IP地址
        char sourceIp[INET_ADDRSTRLEN], destIp[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, ipHeader->saddr, sourceIp, INET_ADDRSTRLEN);
        inet_ntop(AF_INET, ipHeader->daddr, destIp, INET_ADDRSTRLEN);
        
        packet.sourceIp = sourceIp;
        packet.destIp = destIp;
        
        // 获取IP头部长度和TTL
        int ipHeaderLength = (ipHeader->version_ihl & 0x0F) * 4; // IP头部长度（以4字节为单位）
        u_char ttl = ipHeader->ttl;
        
        // 填充网络层详情
        packet.networkLayerDetail = QString("源IP地址: %1\n").arg(packet.sourceIp) +
                                   QString("目的IP地址: %1\n").arg(packet.destIp) +
                                   QString("TTL: %1\n").arg(ttl);
        
        // 解析传输层协议
        const u_char *transportHeaderData = ipHeaderData + ipHeaderLength;
        
        // 根据协议类型进行不同的解析
        switch (ipHeader->protocol) {
        case PROTOCOL_TCP:
            packet.protocol = "TCP";
            packet.networkLayerDetail += "协议: TCP";
            parseTCPPacket(transportHeaderData, length - sizeof(EthernetHeader) - ipHeaderLength, packet);
            break;
        case PROTOCOL_UDP:
            packet.protocol = "UDP";
            packet.networkLayerDetail += "协议: UDP";
            parseUDPPacket(transportHeaderData, length - sizeof(EthernetHeader) - ipHeaderLength, packet);
            break;
        case PROTOCOL_ICMP:
            packet.protocol = "ICMP";
            packet.networkLayerDetail += "协议: ICMP";
            parseICMPPacket(transportHeaderData, length - sizeof(EthernetHeader) - ipHeaderLength, packet);
            break;
        case PROTOCOL_IGMP:
            packet.protocol = "IGMP";
            packet.networkLayerDetail += "协议: IGMP";
            parseIGMPPacket(transportHeaderData, length - sizeof(EthernetHeader) - ipHeaderLength, packet);
            break;
        default:
            packet.protocol = QString("未知(%1)").arg(ipHeader->protocol);
            packet.networkLayerDetail += QString("协议: 未知(%1)").arg(ipHeader->protocol);
            packet.transportLayerDetail = "传输层数据（无法解析）";
            packet.applicationLayerDetail = "应用层数据（无法解析）";
            break;
        }
    } else {
        // 数据包太短，无法解析IP头部
        packet.sourceIp = "";
        packet.destIp = "";
        packet.protocol = "IPv4（不完整）";
        packet.networkLayerDetail = "数据包太短，无法解析IP头部";
        packet.transportLayerDetail = "传输层数据（无法解析）";
        packet.applicationLayerDetail = "应用层数据（无法解析）";
    }
}

// 解析ARP数据包
void PacketCapturer::parseARPPacket(const u_char *packetData, int length, PacketInfo &packet)
{
    // 解析ARP头部
    const u_char *arpHeaderData = packetData + sizeof(EthernetHeader);
    
    // 检查是否有足够的长度来解析ARP头部
    if (length >= static_cast<int>(sizeof(EthernetHeader) + sizeof(ARPHeader))) {
        const ARPHeader *arpHeader = reinterpret_cast<const ARPHeader*>(arpHeaderData);
        
        // 格式化IP地址
        char senderIp[INET_ADDRSTRLEN], targetIp[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, arpHeader->senderIp, senderIp, INET_ADDRSTRLEN);
        inet_ntop(AF_INET, arpHeader->targetIp, targetIp, INET_ADDRSTRLEN);
        
        // 格式化MAC地址
        char senderMac[18], targetMac[18];
        snprintf(senderMac, sizeof(senderMac), "%02x:%02x:%02x:%02x:%02x:%02x",
                 arpHeader->senderMac[0], arpHeader->senderMac[1], arpHeader->senderMac[2],
                 arpHeader->senderMac[3], arpHeader->senderMac[4], arpHeader->senderMac[5]);
        snprintf(targetMac, sizeof(targetMac), "%02x:%02x:%02x:%02x:%02x:%02x",
                 arpHeader->targetMac[0], arpHeader->targetMac[1], arpHeader->targetMac[2],
                 arpHeader->targetMac[3], arpHeader->targetMac[4], arpHeader->targetMac[5]);
        
        // 设置基本信息
        packet.protocol = "ARP";
        packet.sourceIp = senderIp;
        packet.destIp = targetIp;
        
        // 获取操作类型
        u_short operation = ntohs(arpHeader->operation);
        QString opType = (operation == ARP_OP_REQUEST) ? "ARP请求" : 
                         (operation == ARP_OP_REPLY) ? "ARP响应" : 
                         QString("未知(%1)").arg(operation);
        
        // 填充各层详情
        packet.networkLayerDetail = QString("操作类型: %1\n").arg(opType) +
                                   QString("发送方IP地址: %1\n").arg(senderIp) +
                                   QString("发送方MAC地址: %1\n").arg(senderMac) +
                                   QString("目标IP地址: %1\n").arg(targetIp) +
                                   QString("目标MAC地址: %1").arg(targetMac);
        packet.transportLayerDetail = "ARP协议（无传输层）";
        packet.applicationLayerDetail = "ARP协议（无应用层）";
    } else {
        // 数据包太短，无法解析ARP头部
        packet.protocol = "ARP（不完整）";
        packet.networkLayerDetail = "数据包太短，无法解析ARP头部";
        packet.transportLayerDetail = "传输层数据（无法解析）";
        packet.applicationLayerDetail = "应用层数据（无法解析）";
    }
}

// 解析TCP数据包
void PacketCapturer::parseTCPPacket(const u_char *transportHeaderData, int remainingLength, PacketInfo &packet)
{
    // 检查是否有足够的长度来解析TCP头部
    if (remainingLength >= static_cast<int>(sizeof(TCPHeader))) {
        const TCPHeader *tcpHeader = reinterpret_cast<const TCPHeader*>(transportHeaderData);
        int sourcePort = ntohs(tcpHeader->sourcePort);
        int destPort = ntohs(tcpHeader->destPort);
        u_int seq = ntohl(tcpHeader->seq);
        u_int ack = ntohl(tcpHeader->ack);
        u_short window = ntohs(tcpHeader->window);
        u_char flags = tcpHeader->flags;
        
        // 解析TCP标志位
        QString flagsStr;
        if (flags & TCP_FLAG_FIN) flagsStr += "FIN, ";
        if (flags & TCP_FLAG_SYN) flagsStr += "SYN, ";
        if (flags & TCP_FLAG_RST) flagsStr += "RST, ";
        if (flags & TCP_FLAG_PSH) flagsStr += "PSH, ";
        if (flags & TCP_FLAG_ACK) flagsStr += "ACK, ";
        if (flags & TCP_FLAG_URG) flagsStr += "URG, ";
        if (!flagsStr.isEmpty()) flagsStr.chop(2); // 移除最后的逗号和空格
        
        // 填充传输层详情
        packet.transportLayerDetail = QString("协议: TCP\n源端口: %1\n目的端口: %2\n").arg(sourcePort).arg(destPort) +
                                      QString("序列号: %1\n确认号: %2\n窗口大小: %3\n").arg(seq).arg(ack).arg(window);
        if (!flagsStr.isEmpty()) {
            packet.transportLayerDetail += QString("标志位: %1\n").arg(flagsStr);
        }
        
        // 简单检测常见应用层协议
        if (sourcePort == 80 || destPort == 80) {
            packet.applicationLayerDetail = "HTTP协议（端口80）";
        } else if (sourcePort == 443 || destPort == 443) {
            packet.applicationLayerDetail = "HTTPS协议（端口443）";
        } else if (sourcePort == 53 || destPort == 53) {
            packet.applicationLayerDetail = "DNS协议（端口53）";
        } else if (sourcePort == 21 || destPort == 21) {
            packet.applicationLayerDetail = "FTP协议（端口21）";
        } else if (sourcePort == 22 || destPort == 22) {
            packet.applicationLayerDetail = "SSH协议（端口22）";
        } else if (sourcePort == 25 || destPort == 25) {
            packet.applicationLayerDetail = "SMTP协议（端口25）";
        } else if (sourcePort == 110 || destPort == 110) {
            packet.applicationLayerDetail = "POP3协议（端口110）";
        } else if (sourcePort == 143 || destPort == 143) {
            packet.applicationLayerDetail = "IMAP协议（端口143）";
        } else if (sourcePort == 3306 || destPort == 3306) {
            packet.applicationLayerDetail = "MySQL协议（端口3306）";
        } else if (sourcePort == 5432 || destPort == 5432) {
            packet.applicationLayerDetail = "PostgreSQL协议（端口5432）";
        } else if (sourcePort == 27017 || destPort == 27017) {
            packet.applicationLayerDetail = "MongoDB协议（端口27017）";
        } else {
            packet.applicationLayerDetail = QString("TCP数据（端口 %1 → %2）").arg(sourcePort).arg(destPort);
        }
    } else {
        // 数据包太短，无法解析TCP头部
        packet.transportLayerDetail = "TCP头部（不完整）";
        packet.applicationLayerDetail = "应用层数据（无法解析）";
    }
}

// 解析UDP数据包
void PacketCapturer::parseUDPPacket(const u_char *transportHeaderData, int remainingLength, PacketInfo &packet)
{
    // 检查是否有足够的长度来解析UDP头部
    if (remainingLength >= static_cast<int>(sizeof(UDPHeader))) {
        const UDPHeader *udpHeader = reinterpret_cast<const UDPHeader*>(transportHeaderData);
        int sourcePort = ntohs(udpHeader->sourcePort);
        int destPort = ntohs(udpHeader->destPort);
        int udpLength = ntohs(udpHeader->length);
        
        // 填充传输层详情
        packet.transportLayerDetail = QString("协议: UDP\n源端口: %1\n目的端口: %2\nUDP长度: %3\n").arg(sourcePort).arg(destPort).arg(udpLength);
        
        // 简单检测常见应用层协议
        if (sourcePort == 53 || destPort == 53) {
            packet.applicationLayerDetail = "DNS协议（端口53）";
        } else if (sourcePort == 67 || sourcePort == 68 || destPort == 67 || destPort == 68) {
            packet.applicationLayerDetail = "DHCP协议（端口67/68）";
        } else if (sourcePort == 123 || destPort == 123) {
            packet.applicationLayerDetail = "NTP协议（端口123）";
        } else if (sourcePort == 161 || sourcePort == 162 || destPort == 161 || destPort == 162) {
            packet.applicationLayerDetail = "SNMP协议（端口161/162）";
        } else if (sourcePort == 500 || destPort == 500) {
            packet.applicationLayerDetail = "IPsec/IKE协议（端口500）";
        } else if (sourcePort == 1900 || destPort == 1900) {
            packet.applicationLayerDetail = "SSDP协议（端口1900）";
        } else {
            packet.applicationLayerDetail = QString("UDP数据（端口 %1 → %2）").arg(sourcePort).arg(destPort);
        }
    } else {
        // 数据包太短，无法解析UDP头部
        packet.transportLayerDetail = "UDP头部（不完整）";
        packet.applicationLayerDetail = "应用层数据（无法解析）";
    }
}

// 解析ICMP数据包
void PacketCapturer::parseICMPPacket(const u_char *transportHeaderData, int remainingLength, PacketInfo &packet)
{
    // 检查是否有足够的长度来解析ICMP头部
    if (remainingLength >= static_cast<int>(sizeof(ICMPHeader))) {
        const ICMPHeader *icmpHeader = reinterpret_cast<const ICMPHeader*>(transportHeaderData);
        u_char type = icmpHeader->type;
        u_char code = icmpHeader->code;
        u_short id = ntohs(icmpHeader->id);
        u_short sequence = ntohs(icmpHeader->sequence);
        
        // 获取ICMP消息类型描述
        QString typeDesc;
        switch (type) {
        case 0: typeDesc = "回显应答(Echo Reply)";
            break;
        case 3: 
            switch (code) {
            case 0: typeDesc = "目标网络不可达(Network Unreachable)";
                break;
            case 1: typeDesc = "目标主机不可达(Host Unreachable)";
                break;
            case 2: typeDesc = "协议不可达(Protocol Unreachable)";
                break;
            case 3: typeDesc = "端口不可达(Port Unreachable)";
                break;
            default: typeDesc = QString("目标不可达(Unknown Code: %1)").arg(code);
                break;
            }
            break;
        case 4: typeDesc = "源抑制(Source Quench)";
            break;
        case 5: typeDesc = "重定向(Redirect)";
            break;
        case 8: typeDesc = "回显请求(Echo Request)";
            break;
        case 9: typeDesc = "路由器通告(Router Advertisement)";
            break;
        case 10: typeDesc = "路由器请求(Router Solicitation)";
            break;
        case 11: typeDesc = "超时(Time Exceeded)";
            break;
        case 12: typeDesc = "参数问题(Parameter Problem)";
            break;
        case 13: typeDesc = "时间戳请求(Timestamp Request)";
            break;
        case 14: typeDesc = "时间戳应答(Timestamp Reply)";
            break;
        case 17: typeDesc = "地址掩码请求(Address Mask Request)";
            break;
        case 18: typeDesc = "地址掩码应答(Address Mask Reply)";
            break;
        default: typeDesc = QString("未知类型(%1)").arg(type);
            break;
        }
        
        // 填充传输层详情
        packet.transportLayerDetail = QString("协议: ICMP\n类型: %1 (%2)\n代码: %3\n").arg(type).arg(typeDesc).arg(code);
        if (type == 8 || type == 0) {
            // 对于回显请求和应答，添加ID和序列号
            packet.transportLayerDetail += QString("标识符: %1\n序列号: %2\n").arg(id).arg(sequence);
        }
        
        packet.applicationLayerDetail = "ICMP消息（控制消息协议）";
    } else {
        // 数据包太短，无法解析ICMP头部
        packet.transportLayerDetail = "ICMP头部（不完整）";
        packet.applicationLayerDetail = "应用层数据（无法解析）";
    }
}

// 解析IGMP数据包
void PacketCapturer::parseIGMPPacket(const u_char *transportHeaderData, int remainingLength, PacketInfo &packet)
{
    // 检查是否有足够的长度来解析IGMP头部
    if (remainingLength >= static_cast<int>(sizeof(IGMPHeader))) {
        const IGMPHeader *igmpHeader = reinterpret_cast<const IGMPHeader*>(transportHeaderData);
        u_char type = igmpHeader->type;
        u_char maxResponseTime = igmpHeader->maxResponseTime;
        
        // 获取IGMP消息类型描述
        QString typeDesc;
        switch (type) {
        case 0x11: typeDesc = "成员查询(Membership Query)";
            break;
        case 0x12: typeDesc = "v1成员报告(v1 Membership Report)";
            break;
        case 0x16: typeDesc = "v2成员报告(v2 Membership Report)";
            break;
        case 0x17: typeDesc = "离开组(Leave Group)";
            break;
        case 0x22: typeDesc = "v3成员报告(v3 Membership Report)";
            break;
        default: typeDesc = QString("未知类型(0x%1)").arg(type, 0, 16);
            break;
        }
        
        // 格式化组地址
        char groupAddress[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, igmpHeader->groupAddress, groupAddress, INET_ADDRSTRLEN);
        
        // 填充传输层详情
        packet.transportLayerDetail = QString("协议: IGMP\n类型: 0x%1 (%2)\n最大响应时间: %3\n").arg(type, 0, 16).arg(typeDesc).arg(maxResponseTime) +
                                      QString("组地址: %1\n").arg(groupAddress);
        
        packet.applicationLayerDetail = "IGMP消息（Internet组管理协议）";
    } else {
        // 数据包太短，无法解析IGMP头部
        packet.transportLayerDetail = "IGMP头部（不完整）";
        packet.applicationLayerDetail = "应用层数据（无法解析）";
    }
}

// IPv6头部结构体（简化版）
struct IPv6Header {
    u_char  version_traffic_flow[4];  // 版本(4位)、流量类别(8位)、流标签(20位)
    u_short payloadLength;            // 负载长度
    u_char  nextHeader;               // 下一个头部
    u_char  hopLimit;                 // 跳数限制
    u_char  sourceAddress[16];        // 源IPv6地址
    u_char  destinationAddress[16];   // 目的IPv6地址
};  // 40字节

// IPv6扩展头部类型常量
#define IPv6_HEADER_HOPBYHOP 0        // 逐跳选项头部
#define IPv6_HEADER_ICMPV6 58         // ICMPv6头部
#define IPv6_HEADER_NO_NEXT 59        // 无下一个头部
#define IPv6_HEADER_DEST 60           // 目的选项头部
#define IPv6_HEADER_ROUTING 43        // 路由头部
#define IPv6_HEADER_FRAGMENT 44       // 分片头部
#define IPv6_HEADER_AH 51             // 认证头部
#define IPv6_HEADER_ESP 50            // 封装安全载荷头部

// ICMPv6头部结构体（简化版）
struct ICMPv6Header {
    u_char  type;                     // 消息类型
    u_char  code;                     // 消息代码
    u_short checksum;                 // 校验和
};  // 4字节

// IPv6地址转换函数实现
static QString ipv6AddressToString(const u_char* address) {
    char str[INET6_ADDRSTRLEN];
    inet_ntop(AF_INET6, address, str, INET6_ADDRSTRLEN);
    return QString(str);
}

// 解析IPv6数据包
void PacketCapturer::parseIPv6Packet(const u_char *packetData, int length, PacketInfo &packet) {
    // 解析IPv6头部
    const u_char *ipv6HeaderData = packetData + sizeof(EthernetHeader);
    
    // 检查是否有足够的长度来解析IPv6头部
    if (length >= static_cast<int>(sizeof(EthernetHeader) + sizeof(IPv6Header))) {
        const IPv6Header *ipv6Header = reinterpret_cast<const IPv6Header*>(ipv6HeaderData);
        
        // 获取IPv6地址
        packet.sourceIp = ipv6AddressToString(ipv6Header->sourceAddress);
        packet.destIp = ipv6AddressToString(ipv6Header->destinationAddress);
        
        // 获取负载长度和下一个头部类型
        u_short payloadLength = ntohs(ipv6Header->payloadLength);
        u_char nextHeader = ipv6Header->nextHeader;
        u_char hopLimit = ipv6Header->hopLimit;
        
        // 填充网络层详情
        packet.networkLayerDetail = QString("源IPv6地址: %1\n").arg(packet.sourceIp) +
                                   QString("目的IPv6地址: %1\n").arg(packet.destIp) +
                                   QString("负载长度: %1\n").arg(payloadLength) +
                                   QString("跳数限制: %1\n").arg(hopLimit);
        
        // 解析传输层协议或扩展头部
        const u_char *nextHeaderData = ipv6HeaderData + sizeof(IPv6Header);
        int remainingLength = length - sizeof(EthernetHeader) - sizeof(IPv6Header);
        
        // 处理扩展头部
        bool hasExtensionHeaders = false;
        QString extensionHeadersInfo = "";
        
        while (true) {
            // 根据下一个头部类型进行不同的解析
            switch (nextHeader) {
            case PROTOCOL_TCP: {
                packet.protocol = "TCPv6";
                packet.networkLayerDetail += QString("协议: TCPv6\n");
                if (hasExtensionHeaders) {
                    packet.networkLayerDetail += extensionHeadersInfo;
                }
                parseTCPPacket(nextHeaderData, remainingLength, packet);
                return;
            }
            case PROTOCOL_UDP: {
                packet.protocol = "UDPv6";
                packet.networkLayerDetail += QString("协议: UDPv6\n");
                if (hasExtensionHeaders) {
                    packet.networkLayerDetail += extensionHeadersInfo;
                }
                parseUDPPacket(nextHeaderData, remainingLength, packet);
                return;
            }
            case IPv6_HEADER_ICMPV6: {
                packet.protocol = "ICMPv6";
                packet.networkLayerDetail += QString("协议: ICMPv6\n");
                if (hasExtensionHeaders) {
                    packet.networkLayerDetail += extensionHeadersInfo;
                }
                parseICMPv6Packet(nextHeaderData, remainingLength, packet);
                return;
            }
            case IPv6_HEADER_HOPBYHOP: {
                // 逐跳选项头部（简化处理）
                hasExtensionHeaders = true;
                extensionHeadersInfo += "扩展头部: 逐跳选项\n";
                // 头部长度（以8字节为单位，不包括第一个8字节）
                u_char headerLength = nextHeaderData[1];
                nextHeader = nextHeaderData[0];
                nextHeaderData += 8 + headerLength * 8;
                remainingLength -= 8 + headerLength * 8;
                break;
            }
            case IPv6_HEADER_ROUTING: {
                // 路由头部（简化处理）
                hasExtensionHeaders = true;
                extensionHeadersInfo += "扩展头部: 路由\n";
                // 头部长度（以8字节为单位，不包括第一个8字节）
                u_char routingHeaderLength = nextHeaderData[1];
                nextHeader = nextHeaderData[0];
                nextHeaderData += 8 + routingHeaderLength * 8;
                remainingLength -= 8 + routingHeaderLength * 8;
                break;
            }
            case IPv6_HEADER_FRAGMENT: {
                // 分片头部（简化处理）
                hasExtensionHeaders = true;
                extensionHeadersInfo += "扩展头部: 分片\n";
                nextHeader = nextHeaderData[0];
                nextHeaderData += 8;  // 分片头部固定8字节
                remainingLength -= 8;
                break;
            }
            case IPv6_HEADER_DEST: {
                // 目的选项头部（简化处理）
                hasExtensionHeaders = true;
                extensionHeadersInfo += "扩展头部: 目的选项\n";
                // 头部长度（以8字节为单位，不包括第一个8字节）
                u_char destHeaderLength = nextHeaderData[1];
                nextHeader = nextHeaderData[0];
                nextHeaderData += 8 + destHeaderLength * 8;
                remainingLength -= 8 + destHeaderLength * 8;
                break;
            }
            case IPv6_HEADER_AH: {
                // 认证头部（简化处理）
                hasExtensionHeaders = true;
                extensionHeadersInfo += "扩展头部: 认证\n";
                // 头部长度（以4字节为单位，减去2）
                u_char ahLength = nextHeaderData[1];
                nextHeader = nextHeaderData[0];
                nextHeaderData += (ahLength + 2) * 4;
                remainingLength -= (ahLength + 2) * 4;
                break;
            }
            case IPv6_HEADER_ESP: {
                // 封装安全载荷头部（简化处理）
                hasExtensionHeaders = true;
                extensionHeadersInfo += "扩展头部: 封装安全载荷\n";
                // ESP头部至少8字节，这里简化处理
                nextHeader = IPv6_HEADER_NO_NEXT;  // 无法确定ESP后的头部类型
                packet.protocol = "ESPv6";
                packet.networkLayerDetail += "协议: ESPv6\n";
                if (hasExtensionHeaders) {
                    packet.networkLayerDetail += extensionHeadersInfo;
                }
                packet.transportLayerDetail = "传输层数据（ESP加密）";
                packet.applicationLayerDetail = "应用层数据（ESP加密）";
                return;
            }
            case IPv6_HEADER_NO_NEXT: {
                // 无下一个头部
                packet.protocol = "IPv6";
                packet.networkLayerDetail += "协议: IPv6\n";
                if (hasExtensionHeaders) {
                    packet.networkLayerDetail += extensionHeadersInfo;
                }
                packet.transportLayerDetail = "无传输层数据";
                packet.applicationLayerDetail = "无应用层数据";
                return;
            }
            default: {
                // 未知头部类型
                packet.protocol = QString("IPv6-%1").arg(nextHeader);
                packet.networkLayerDetail += QString("协议: 未知(%1)\n").arg(nextHeader);
                if (hasExtensionHeaders) {
                    packet.networkLayerDetail += extensionHeadersInfo;
                }
                packet.transportLayerDetail = "传输层数据（无法解析）";
                packet.applicationLayerDetail = "应用层数据（无法解析）";
                return;
            }
            }
            
            // 检查剩余长度是否足够
            if (remainingLength < 1) {
                packet.protocol = "IPv6（不完整）";
                packet.transportLayerDetail = "传输层数据（不完整）";
                packet.applicationLayerDetail = "应用层数据（无法解析）";
                return;
            }
        }
    } else {
        // 数据包太短，无法解析IPv6头部
        packet.sourceIp = "";
        packet.destIp = "";
        packet.protocol = "IPv6（不完整）";
        packet.networkLayerDetail = "数据包太短，无法解析IPv6头部";
        packet.transportLayerDetail = "传输层数据（无法解析）";
        packet.applicationLayerDetail = "应用层数据（无法解析）";
    }
}

// 解析ICMPv6数据包
// 获取ICMPv6类型描述
static QString getICMPv6TypeDescription(u_char type, u_char /*code*/);

// 解析ICMPv6数据包
void PacketCapturer::parseICMPv6Packet(const u_char *icmpHeaderData, int remainingLength, PacketInfo &packet) {
    // 检查是否有足够的长度来解析ICMPv6头部
    if (remainingLength >= static_cast<int>(sizeof(ICMPv6Header))) {
        const ICMPv6Header *icmpHeader = reinterpret_cast<const ICMPv6Header*>(icmpHeaderData);
        
        u_char type = icmpHeader->type;
        u_char code = icmpHeader->code;
        u_short checksum = ntohs(icmpHeader->checksum);
        
        // 获取ICMPv6类型描述
        QString typeDesc = getICMPv6TypeDescription(type, code);
        
        // 填充传输层详情
        packet.transportLayerDetail = QString("ICMPv6类型: %1 (0x%2)\n").arg(typeDesc).arg(type, 0, 16) +
                                     QString("代码: %1\n").arg(code) +
                                     QString("校验和: 0x%1\n").arg(checksum, 0, 16);
        
        // 检查是否有足够长度获取更多信息
        if (remainingLength > static_cast<int>(sizeof(ICMPv6Header))) {
            // 对于某些类型的ICMPv6消息，我们可以解析更多信息
            switch (type) {
            case 128:  // Echo Request
                if (remainingLength >= static_cast<int>(sizeof(ICMPv6Header) + 4)) {
                    u_short id = ntohs(*(reinterpret_cast<const u_short*>(icmpHeaderData + sizeof(ICMPv6Header))));
                    u_short seq = ntohs(*(reinterpret_cast<const u_short*>(icmpHeaderData + sizeof(ICMPv6Header) + 2)));
                    packet.transportLayerDetail += QString("标识符: %1\n").arg(id);
                    packet.transportLayerDetail += QString("序列号: %1\n").arg(seq);
                }
                break;
            case 129:  // Echo Reply
                if (remainingLength >= static_cast<int>(sizeof(ICMPv6Header) + 4)) {
                    u_short id = ntohs(*(reinterpret_cast<const u_short*>(icmpHeaderData + sizeof(ICMPv6Header))));
                    u_short seq = ntohs(*(reinterpret_cast<const u_short*>(icmpHeaderData + sizeof(ICMPv6Header) + 2)));
                    packet.transportLayerDetail += QString("标识符: %1\n").arg(id);
                    packet.transportLayerDetail += QString("序列号: %1\n").arg(seq);
                }
                break;
            case 135:  // Neighbor Solicitation
            case 136:  // Neighbor Advertisement
            case 133:  // Router Solicitation
            case 134:  // Router Advertisement
                // 这些是IPv6邻居发现协议的一部分，这里简化处理
                packet.transportLayerDetail += "IPv6邻居发现消息\n";
                break;
            default:
                // 其他类型的ICMPv6消息
                packet.transportLayerDetail += "ICMPv6消息（未详细解析）\n";
                break;
            }
        }
        
        // 应用层详情（ICMPv6通常没有应用层数据）
        packet.applicationLayerDetail = "无应用层数据";
    } else {
        // 数据包太短，无法解析ICMPv6头部
        packet.transportLayerDetail = "ICMPv6头部（不完整）";
        packet.applicationLayerDetail = "应用层数据（无法解析）";
    }
}

// 获取ICMPv6类型描述
static QString getICMPv6TypeDescription(u_char type, u_char code) {
    Q_UNUSED(code);  // 标记参数为未使用
    switch (type) {
    case 1: return "目的地不可达";
    case 2: return "数据包太长";
    case 3: return "超时";
    case 4: return "参数问题";
    case 128: return "回显请求 (Ping)";
    case 129: return "回显应答 (Ping Reply)";
    case 130: return "路由器请求";
    case 131: return "路由器通告";
    case 132: return "邻居请求";
    case 133: return "邻居通告";
    case 134: return "重定向消息";
    case 135: return "ICMPv6消息（保留）";
    case 136: return "ICMPv6消息（保留）";
    case 137: return "多播侦听器查询";
    case 138: return "多播侦听器报告";
    case 139: return "多播侦听器完成";
    case 140: return "路由器重命名请求";
    case 141: return "路由器重命名应答";
    case 142: return "ICMPv6消息（保留）";
    case 143: return "节点信息请求";
    case 144: return "节点信息应答";
    case 145: return "反向邻居发现请求";
    case 146: return "反向邻居发现应答";
    case 147: return "反向邻居发现确认";
    default: return QString("未知(%1)").arg(type);
    }
}